import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Tree, Row, Col, Card, Spin } from 'antd';

@connect(({ rule, loading }) => (
  {
    rule,
    loading: loading.models.rule,
  }
))
export default class AddRole extends PureComponent {
  state = {
    autoExpandParent: true,
    checkedKeys: [],
    selectedKeys: [],
    changeLoading: false,
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/roleList',
    });
  }
  onCheck = (checkedKeys, info) => {
    info.checkedNodes.map((item) => {
      if (item.props && item.props.id) {
        console.log(item.props.id);
      }
    });
    this.setState({ checkedKeys });
    this.toggle(true);
    setTimeout(() => {
      this.toggle(false);
    }, 3000);
  }
  onSelect = (selectedKeys, info) => {
    console.log('onSelect', info);
    this.setState({ selectedKeys });
  }
  toggle = (value) => {
    this.setState({ changeLoading: value });
  }
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <Tree.TreeNode title={item.title} key={item.key} dataRef={item} selectable={false}>
            {this.renderTreeNodes(item.children)}
          </Tree.TreeNode>
        );
      }
      return <Tree.TreeNode {...item} />;
    });
  }
  render() {
    const { roleList } = this.props.rule;
    const { changeLoading } = this.state;
    return (
      <Card title="权限树">
        <Row>
          <Col span={12} offset={6}>
            <Spin spinning={changeLoading} delay={500} >
              <Tree
                checkable
                autoExpandParent={this.state.autoExpandParent}
                onCheck={this.onCheck}
                checkedKeys={this.state.checkedKeys}
                onSelect={this.onSelect}
                selectedKeys={this.state.selectedKeys}
              >
                {this.renderTreeNodes(roleList)}
              </Tree>
            </Spin>
          </Col>
        </Row>
      </Card>
    );
  }
}
